<?php

	class WSServer
	{
		public $serv;
		public $ip;
		public $port;
		public $clis = [];
		public $queue = [];
		public function __construct($ip='0.0.0.0',$port='1234')
		{
			$this->ip = $ip;
			$this->port = $port;
			$this->serv = new swoole_websocket_server($this->ip,$this->port);
			$this->listen();
			$this->serv->start();
		}

		public function listen()
		{
			$this->serv->on('workerStart',function(){
				swoole_timer_tick(1000,[$this,'push']);
				echo "ok\n";
			});
			$this->serv->on('request',[$this,'request']);
			$this->serv->on('open',[$this,'open']);
			$this->serv->on('message',[$this,'message']);
			$this->serv->on('close',[$this,'close']);
		}

		public function open($serv,$req)
		{
			$this->clis[$req->fd] = $req->fd;
			echo "Serv: {$req->fd} connect\n";
			$this->serv->push($req->fd,"welcome!");
		}

		public function message($serv,$frame)
		{
			if(stripos($frame->data,'|')!==false){
				$data = explode('|',$frame->data);
				$this->queue[] =['fd'=>$data[0],'msg'=>$data[1]];
			}

			foreach($serv->connections as $fd){
				$this->serv->push($fd,"Serv: {$frame->data}");
			}

		}

		public function close($serv,$fd)
		{
			unset($this->clis[$fd]);
			foreach($serv->connections as $fd){
				$this->serv->push($fd,"Serv: {$fd} is logout");
			}
		}
		/**
		 * 推送方法 具体消息队列应换成redis
		 * @return void
		 */
		public function push()
		{
			while($data = array_shift($this->queue))
			{
				$this->serv->push($data['fd'],$data['msg']);
			}
		}

		public function request($request,$response)
		{
			print_r($request);
			$response->end('<h1>hello</h1>');
		}

	}
	new WSServer;
